<template>
  <a-spin :spinning="loading" v-if="data" class="w-[100%]">
    <template v-if="componentType === 'input'">
      <a-input
        @keydown.enter="onChange"
        @blur="onChange"
        v-model:value="data.modelValue"
        class="w-[100%]"
      ></a-input>
    </template>
    <template v-else-if="componentType === 'select'">
      <a-select
        @change="onChange"
        v-model:value="data.modelValue"
        :options="props.options"
        class="w-[100%]"
      ></a-select>
    </template>
    <template v-else-if="componentType === 'radio-group'">
      <!--  @vue-ignore  -->
      <a-radio-group
        @change="onChange"
        v-model:value="data.modelValue"
        :options="props.options"
        class="w-[100%]"
      ></a-radio-group>
    </template>
    <template v-else-if="componentType === 'checkbox'">
      <a-checkbox
        @keydown.enter="onChange"
        @change="onChange"
        v-model:checked="data.modelValue"
      ></a-checkbox>
    </template>
  </a-spin>
</template>

<script setup lang="ts">
import type { PendingUpdates } from '@/types/system';
import { response } from '@/utils/table/table';
import { useCloned } from '@vueuse/core';

const emit = defineEmits(['change', 'failure', 'update:modelValue']);

const loading = ref(false);

/* 待更新的值 */
const data = ref<PendingUpdates>({
  fieldName: '',
  id: '',
  modelValue: '',
  componentType: 'input',
  updateFunc: () => {},
});

const props = withDefaults(defineProps<PendingUpdates>(), {
  componentType: 'input',
});
/* 成功更新后的回调 */
const onChange = async () => {
  const cloneData = useCloned(data.value).cloned.value;
  /* 当值改变时,触发 */
  if (data.value.modelValue !== props.modelValue) {
    try {
      if (props.updateFunc) {
        loading.value = true;
        await response(props.updateFunc, cloneData);
        emit('change', cloneData);
        emit('update:modelValue', cloneData.modelValue);
        loading.value = false;
      }
    } catch (error) {
      emit('failure', cloneData.modelValue);
      loading.value = false;
    }
  }
};

watch(
  props,
  () => {
    data.value = useCloned(props).cloned.value;
  },
  {
    deep: true,
    immediate: true,
  },
);
</script>

<style lang="scss" scoped></style>
